/**
 * Created by arnold.zhu on 6/28/2017.
 */
import React from 'react';
import {hashHistory} from 'react-router';
import {Form, Input, Button, Row, Col} from 'antd';

import LoginService from '../../service/login/loginService.js';

const FormItem = Form.Item;

var LoginComponent = React.createClass({
  componentWillMount: function () {
    if (localStorage.getItem('userInfo') != null) {
      hashHistory.push('/');
    }
  },
  handleSubmit: function (e) {
    e.preventDefault();
    this.props.form.validateFields((errors, values) => {
      if (errors) {
        console.log('Errors in form!!!');
        return;
      }
      LoginService.login(values).then(data => {
        if (data) {
          localStorage.setItem('userInfo', JSON.stringify({'username': 'arnold'}));
          hashHistory.push('/main/home');
        }
      }).catch(err => {
        console.info(err);
      });
    });
  },
  render: function () {
    const {getFieldDecorator} = this.props.form;
    return (
      <Row>
        <Col span={24}>
          <div>
            <Form horizontal>
              <FormItem
                label="username"
                labelCol={{span: 2, offset: 7}}
                wrapperCol={{span: 5}}>
                {getFieldDecorator('Username', {
                  rules: [
                    {required: true, message: 'Please enter your Username'}
                  ]
                })(<Input />)}
              </FormItem>
              <FormItem
                label="password"
                labelCol={{span: 2, offset: 7}}
                wrapperCol={{span: 5}}>
                {getFieldDecorator('Password', {
                  rules: [
                    {required: true, message: 'Please enter your password'}
                  ]
                })(
                  <Input type="password" autoComplete="off"/>
                )}
              </FormItem>
              <FormItem wrapperCol={{span: 1, offset: 10}}>
                <Button type="primary" className="ant-custom-loginBtn" onClick={this.handleSubmit}>Login</Button>
              </FormItem>
            </Form>
          </div>
        </Col>
      </Row>

    )
  }
});

LoginComponent = Form.create()(LoginComponent);

export default LoginComponent;